package com.jy.modules.cims.component.image.service;

import java.util.Observable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.common.sysUtils.SpringContextUtils;
import com.jy.modules.cims.component.image.TransferImagesDto;
import com.jy.modules.cims.component.image.TransferImagesHelper;
import com.jy.modules.cims.component.image.TransferImagesQueue;
import com.jy.modules.cims.sysUtils.ImgurFtpConfigInfo;

/**
 * @description 上传服务
 * @author shengzhoutao
 * @date 2015-09-29
 */
@Component
public class UploadImagesToFTPService extends Observable {
	private static Logger logger = LoggerFactory.getLogger(UploadImagesToFTPService.class);
	
	@Autowired
	private SpringContextUtils springContextUtils;
	
	/**
	 * @description
	 * @param transferImagesDto
	 */
	public void doSomething(TransferImagesDto transferImagesDto) {
		String contractNo = transferImagesDto.getContractNo();
		String cooperorgCode = transferImagesDto.getCooperorgCode();
		TransferImagesHelper transferImagesHelper = springContextUtils.getBean(TransferImagesHelper.class);
		ImgurFtpConfigInfo imgurFtpConfigInfo = null;
		try {
			// 根据合作机构编码获取配置文件信息
			imgurFtpConfigInfo = transferImagesHelper.getImgurFtpConfigInfoByCooperorgCode(cooperorgCode);
			String ftpCompressed = imgurFtpConfigInfo.getFtpCompressed();

			// 上传文件到Ftp
			boolean uploadSuccess = transferImagesHelper.uploadImagesFile(imgurFtpConfigInfo, transferImagesDto);
			// boolean uploadSuccess = true;

			String accessoryFtpUrl = "";// 记录上传到文件服务器的路径地址

			// 上传文件成功
			if (uploadSuccess) {
				logger.info("上传文件成功的合同号:" + transferImagesDto.getContractNo());
				
				//
				if (CimsConstant.COOPERORG_CODE_TBJ.equals(cooperorgCode)) {
					// 放入附件列表队列
					TransferImagesQueue.attachQueue.offer(transferImagesDto);
				}
				
				// 上传压缩包影像文件，ZIP文件上传FTP的目录: .../日期/包名/
				String ftpDir = transferImagesHelper.getFtpDir(imgurFtpConfigInfo, transferImagesDto);
				if (TransferImagesHelper.FTP_COMPRESSED_YES.equalsIgnoreCase(ftpCompressed)) {
					accessoryFtpUrl = SimpleStringUtils.append(ftpDir, contractNo, "_ok.zip");
				} else {
					accessoryFtpUrl = ftpDir;
				}

				transferImagesDto.setAccessoryFtpUrl(accessoryFtpUrl);

				
				// 通知观察者修改处理状态
				setChanged();
				notifyObservers(transferImagesDto);
			}//
		} catch (Exception e) {
			logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e);
		} finally {
			// 上传完文件，清理队列数据和本地文件
			transferImagesHelper.delDealData(imgurFtpConfigInfo, transferImagesDto);
		}// //
	}
}
